import re
import time
import os
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
from configs.other_config import REGEX_FILE_PATH, REGEX_FOLDER_PATH
from instruction.utils import load_json_file


# 预编译正则规则
def precompiled_regex_relus():
    # 存储编译后的规则
    rules = {}

    # 遍历意图和规则
    for intent, intent_rules in regex_rules.items():
        compiled_intent_rules = [re.compile(rule, re.IGNORECASE) for rule in intent_rules]
        rules[intent] = compiled_intent_rules

    return rules


# 读取正则json文件
regex_rules = load_json_file(REGEX_FILE_PATH)
# 预编译正则规则
try:
    compiled_rules = precompiled_regex_relus()
    # 正则json文件是否正常
    regex_json = True
except:
    regex_json = False


class FileEventHandler(FileSystemEventHandler):
    def on_modified(self, event):
        global regex_rules, compiled_rules, regex_json
        if event.src_path == REGEX_FILE_PATH:
            try:
                regex_json = True
                # 读取正则json文件
                regex_rules = load_json_file(REGEX_FILE_PATH)
                # 预编译正则规则
                compiled_rules = precompiled_regex_relus()
                # 文件修改时间
                modification_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                log_message = f"{os.path.basename(REGEX_FILE_PATH)} modified at {modification_time}"
                print(log_message)
            except:
                regex_json = False
                print(f"There is a problem with the {os.path.basename(REGEX_FILE_PATH)} file.")


observer = Observer()
event_handler = FileEventHandler()
observer.schedule(event_handler, REGEX_FOLDER_PATH, True)
observer.start()

# 天气9正则规则
weather_regex_rules = [
    re.compile(
        r'((.*(小卡)*[，。！？]?(播报|告诉我|讲一下|说一下)(现在|(.天))?.?天气(咋|怎么)?样?(预报)?(吗|啊)?[，。！？]?(小卡)?)|当前天气).*'),
    re.compile(r'.*(小卡)*[，。！？]?(播报|告诉我|讲一下|说一下)?(现在|(.天))?.?气温(吗|啊)?[，。！？]?(小卡)?.*'),
    re.compile(r'^(小卡)*[，。！？]?(播报|告诉我|讲一下|说一下)?(现在|(.天))?.?温度(吗|啊)?[，。！？]?(小卡)?$'),
    re.compile(r'.*(今天|现在)?((天气|温度)((怎么|咋)样|好吗)|适合外出吗|(几|多少)度).*'),
    re.compile(r'^(小卡)*[，。！？]?(天气|温度)[？，。！]?$')
]


# 天气9
async def weather_relu(prompt):
    weather_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["weather"]:
            if re.match(i, prompt):
                return '9'
    except:
        for i in weather_regex_rules:
            if re.match(i, prompt):
                return '9'
    return None


# 时间11正则规则
time_regex_rules = [
    re.compile(
        r'^(小卡)*[，。！？]?(((播报|告诉我|讲一下|说一下)?(当前|现在)?.?(什么)?时间(吗|啊|了)?[，。！？]?(小卡)?$)|当前时间|现在是?什么(时候|时间)(了|呢)啊?|现在是?什么(时候|时间)(了|呢)?啊?)[，。！？]?$'),
    re.compile(r'.*(小卡)*[，。！？]?(告诉我|播报|讲一下|说一下)?.*几点钟?了?(吗|啊)?[，。！？]?(小卡)?$'),
    re.compile(r'.*(小卡)*[，。！？]?(告诉我|播报|讲一下|说一下)?.*时辰了?(吗|啊)?[，。！？]?(小卡)?$')
]


# 时间11
async def time_relu(prompt):
    time_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["time"]:
            if re.match(i, prompt):
                return '11'
    except:
        for i in time_regex_rules:
            if re.match(i, prompt):
                return '11'
    return None


# 日期、星期几正则规则
date_regex_relus = [
    re.compile(r'^(小卡)*.?[，。！？]*(今天|现在|今儿?个)?(几月)?(几号了?|(周|星期|礼拜)几)(啊|呢|呀)?[？，。！]?$')
]


async def date_relu(prompt):
    date_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["date"]:
            if re.match(i, prompt):
                return 'date'
    except:
        for i in date_regex_relus:
            if re.match(i, prompt):
                return 'date'
    return None


# 附近/位置问题正则规则
neighborhood_problem_regex_relus = [
    re.compile(r'.*(附近|身边|旁边|周围|边上)(哪里)?有.*'),
    re.compile(r'^(小卡)*[，。！？]?(当前)?位置[？，。！]?$'),
    re.compile(r'.*(小卡)*[，。！？]?我(现在|当前)(位置)?在哪[？，。！]?.*')
]


# 附近问题
async def neighborhood_problem_relu(prompt):
    neighborhood_problem_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["neighborhood_problem"]:
            if re.match(i, prompt):
                return '附近'
    except:
        for i in neighborhood_problem_regex_relus:
            if re.match(i, prompt):
                return '附近'
    return None

# 跳舞54正则规则
dance_regex_relus = [
    re.compile(r'.*(展示)?(舞蹈|(跳|来)一?(个|支|段)舞).*'),
    re.compile(r'.*你(能|会)跳舞吗[？，。！]?'),
    re.compile(r'^(小+卡)*[？，。！]?跳舞[？，。！]?')
]


# 跳舞54
async def dance_relu(prompt):
    dance_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["dance"]:
            if re.match(i, prompt):
                return '54'
    except:
        for i in dance_regex_relus:
            if re.match(i, prompt):
                return '54'
    return None

# 打开照片墙73
open_photo_wall_regex_relus = [
    re.compile(r'.*(打开|前往)照片墙.*')
]


# 打开照片墙73
async def open_photo_wall_rule(prompt):
    try:
        for i in compiled_rules["open_photo_wall"]:
            if re.match(i, prompt):
                return '73'
    except:
        for i in open_photo_wall_regex_relus:
            if re.match(i, prompt):
                return '73'
    return None


# 打开公司介绍74
open_company_profile_regex_relus = [
    re.compile(r'.*(打开|前往)公司介绍.*')
]


# 打开公司介绍74
async def open_company_profile_rule(prompt):
    try:
        for i in compiled_rules["open_company_profile"]:
            if re.match(i, prompt):
                return '74'
    except:
        for i in open_company_profile_regex_relus:
            if re.match(i, prompt):
                return '74'
    return None


# 打开品牌历史75
open_brand_history_regex_relus = [
    re.compile(r'.*(打开|前往)品牌历史.*')
]


# 打开品牌历史75
async def open_brand_history_rule(prompt):
    try:
        for i in compiled_rules["open_brand_history"]:
            if re.match(i, prompt):
                return '75'
    except:
        for i in open_brand_history_regex_relus:
            if re.match(i, prompt):
                return '75'
    return None


# 打开产品介绍76
open_product_introduction_regex_relus = [
    re.compile(r'.*(打开|前往)产品介绍.*')
]


# 打开产品介绍76
async def open_product_introduction_rule(prompt):
    try:
        for i in compiled_rules["open_product_introduction"]:
            if re.match(i, prompt):
                return '76'
    except:
        for i in open_product_introduction_regex_relus:
            if re.match(i, prompt):
                return '76'
    return None


# 意图识别
async def intent_recognition(prompt):
    result = await dance_relu(prompt)
    if result is not None:
        return result

    result = await open_photo_wall_rule(prompt)
    if result is not None:
        return result

    result = await open_company_profile_rule(prompt)
    if result is not None:
        return result

    result = await open_brand_history_rule(prompt)
    if result is not None:
        return result

    result = await open_product_introduction_rule(prompt)
    if result is not None:
        return result

    # 如果没有匹配到任何意图，则返回None
    return None
